package com.tanhua.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.commons.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Value("#{'${gateway.excludedUrls}'.split(',')}")
    private List<String> excludedUrls; //不需要校验的请求集合

    //过滤器核心业务代码
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //排除不需要权限校验的请求，比如：登录，退出
        String path = exchange.getRequest().getURI().getPath(); //获取当前请求链接
        System.out.println("拦截到请求："+path);
        if (excludedUrls.contains(path)){
            System.out.println("检测到当前请求无需处理，放行");
            return chain.filter(exchange);
        }
        System.out.println("检测到当前请求需要处理，Token校验中...");
        //获取token并校验
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        //由于前端人员习惯在token字符串前面加上“Bearer ”，这样我们获取的token字符串就是"Bearer token字符串"，所以我们需要先处理一下token字符串
        if (!StringUtils.isEmpty(token)){
            token = token.replaceAll("Bearer ","");
        }
        //校验token
        boolean flag = JwtUtils.verifyToken(token);
        if (!flag){
            System.out.println("Token校验失败，详情请查看失败信息");
            //失败，响应错误状态：401
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode", 401);
            responseData.put("errMessage", "用户未登录");
            return responseError(exchange.getResponse(),responseData);
        }
        System.out.println("Token校验成功，该次请求通过！");
        //成功，放行
        return chain.filter(exchange);
    }


    //响应错误数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
    //配置过滤器执行顺序
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }



}
